﻿using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace X23.Util.SerializationUtil
{
    /// <summary>
    /// 序列化
    /// </summary>
    public static class SerializationUtil
    {
        /// <summary>
        /// 将对象序列化为Json字符串
        /// </summary>
        /// <param name="data"></param>
        /// <param name="formatDateTime">转换时间格式 默认yyyy-MM-dd HH:mm:ss</param>
        /// <returns></returns>
        public static string ToJson(this object data, string formatDateTime = "yyyy-MM-dd HH:mm:ss")
        {
            if (data is string)
            {
                return data.ToString();
            }

            //时间处理
            var timeConverter = new IsoDateTimeConverter { DateTimeFormat = formatDateTime };
            return JsonConvert.SerializeObject(data, Formatting.Indented, timeConverter);
        }

        /// <summary>
        ///  JSON反序列化
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="json"></param>
        /// <returns></returns>
        public static T ToObjet<T>(this string json)
        {
            return JsonConvert.DeserializeObject<T>(json);
        }

        /// <summary>
        /// 序列化自动映射
        /// </summary>
        /// <typeparam name="TDestination"></typeparam>
        /// <param name="source"></param>
        /// <returns></returns>
        public static TDestination SerializationMapTo<TDestination>(this object source)
        {
            var sourceJson = source.ToJson();
            var destinationObj = sourceJson.ToObjet<TDestination>();
            return destinationObj;
        }
    }
}
